#include "client.h"
#include "ui_client.h"
#include <QDebug>

#include <QFileDialog>
#include <QFileInfo>
#include <QFile>


Client::Client(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Client)
{
    ui->setupUi(this);

    this->setWindowTitle("客户端");

    ui->chooseBtn->setEnabled(false);
    ui->uploadBtn->setEnabled(false);

    this->clientSocket = new QTcpSocket(this);

    // 2. 点击"连接服务器"按钮时，进行与服务器的链接操作
    connect(ui->connectBtn, &QPushButton::clicked, [this](){
        this->clientSocket->connectToHost("127.0.0.1", 8888);
    });

    // 4. 一旦成功与服务器端链接，则会触发connected信号
    connect(this->clientSocket, &QTcpSocket::connected, [this](){
        ui->textEdit->setText("已成功链接服务器");
        ui->chooseBtn->setEnabled(true);
        ui->connectBtn->setEnabled(false);
    });

    // 点击"选择文件"按钮，弹出文件选择框
    // 得到用户选择的问价路径，并将文件名一起发送给服务器端
    connect(ui->chooseBtn, &QPushButton::clicked, [this](){
        // 打开问价选择框，得到用户选择的文件
        this->filePath = QFileDialog::getOpenFileName(this, "选择要上传的文件", ".");
        // 初始化数据
        ui->uploadBtn->setEnabled(true);
        ui->progressBar->setValue(0);
        this->uploadedSize = 0;

        if (this->filePath.isEmpty())
        {
            return;
        }
        QFileInfo info(this->filePath);
        this->fileSize = info.size();
        QString fileName =QString("!@***#head!!!!##%1##%2")
                .arg(info.fileName()).arg(this->fileSize);


        // 写入socket就是发送给服务器端
        this->clientSocket->write(fileName.toUtf8());

    });

    // 点击"上传"按钮，循环读取文件内容，并传输到服务器端
    connect(ui->uploadBtn, &QPushButton::clicked, [this](){
        ui->uploadBtn->setEnabled(false);
        QFile file(this->filePath);
        file.open(QIODevice::ReadOnly);

        // 循环按行读取文件内容，并写入socket
        while (!file.atEnd())
        {
            QByteArray buf = file.readLine();
            this->uploadedSize += this->clientSocket->write(buf);

            // 设置进度条
            ui->progressBar->setValue(this->uploadedSize * 100 / this->fileSize);
        }
    });
}

Client::~Client()
{
    delete ui;
}
